package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.LvRateDao;
import com.framework.entity.sys.SysAgentGrade;
import com.framework.entity.sys.SysLvRate;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.entity.tran.TranTransactionInfo;
import com.framework.service.AgentGradeService;
import com.framework.service.AgentService;
import com.framework.service.LvRateService;
import com.framework.service.TransactionInfoService;
import com.framework.service.yhbservice.YhbUserTerminalRelationService;
import com.framework.utils.DateUtils;
import com.framework.view.PidRateView;
import com.framework.yhbEntity.user.YhbUserTerminalRelation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service("lvRateService")
@Slf4j
public class LvRateServiceImpl extends ServiceImpl<LvRateDao, SysLvRate> implements LvRateService {

    @Autowired
    private AgentService agentService;
    @Autowired
    private AgentGradeService agentGradeService;

    @Autowired
    private YhbUserTerminalRelationService yhbUserTerminalRelationService;

    @Autowired
    private TransactionInfoService transactionInfoService;


    @Override
    public SysLvRate queryRate(Long agentId, Long deptId, Integer terminalType, String isVip) {
        SysAgentGrade agentGrade = agentGradeService.queryGradeByAgentId(agentId);
        if (agentGrade != null) {
            Integer thisGrade = agentGrade.getThisGrade();
            SysLvRate sysLvRate = new SysLvRate();
            sysLvRate.setDeptId(deptId);
            sysLvRate.setLv(thisGrade);
            sysLvRate.setTerminalType(terminalType);
            sysLvRate.setIsVip(isVip);
            SysLvRate lvRate = baseMapper.selectOne(sysLvRate);
            System.out.print("======渠道" + deptId + "===========" + terminalType + "类型产品==============");
            return lvRate;
        } else {
            System.out.print("======================" + agentId + "代理商没有等级=====================");
            return null;
        }
    }

    @Override
    public List<SysLvRate> queryLvList(Long deptId) {
        return baseMapper.queryLvList(deptId);
    }

    @Override
    public BigDecimal queryYhbRate(String sn, Long agentId, Long deptId, int terminalType, String isVip) {
        YhbUserTerminalRelation r = yhbUserTerminalRelationService.queryRelationBySn(sn);

        if (r.getIsUse().intValue() == 0) {
            return new BigDecimal("0.00");
        }
        SysAgentGrade agentGrade = agentGradeService.queryGradeByAgentId(agentId);
        if (agentGrade != null) {
            Integer thisGrade = agentGrade.getThisGrade();
            SysLvRate sysLvRate = new SysLvRate();
            sysLvRate.setDeptId(deptId);
            sysLvRate.setLv(thisGrade);
            sysLvRate.setTerminalType(terminalType);
            sysLvRate.setIsVip(isVip);
            SysLvRate lvRate = baseMapper.selectOne(sysLvRate);
            System.out.print("======================" + terminalType + "类型产品:用户宝=" + lvRate.getYhbRate() + "====================");
            return lvRate.getYhbRate();
        } else {
            System.out.print("======================" + agentId + "代理商没有等级=====================");
            return new BigDecimal("0.00");
        }

    }

    @Override
    public List<PidRateView> queryPidRate(Long agentId, int terminalType, String isVip) {
        return baseMapper.queryPidRate(agentId, terminalType, isVip);
    }

    @Override
    public SysLvRate getSysLvRate(TranTransactionInfo tranTransactionInfo, Long agentId) {
        SysLvRate lvRate;
        Long deptId = tranTransactionInfo.getDeptId();
        BigDecimal XINGPOS = new BigDecimal("50.00");
        //百易的星pos分润
        if (deptId.equals(1L) && tranTransactionInfo.getTerminalType() == 3) {
            if ((tranTransactionInfo.getAmount().compareTo(XINGPOS) == -1) || tranTransactionInfo.getAmount().compareTo(XINGPOS) == 0) {
                lvRate = new SysLvRate();
                lvRate.setDeptId(1L);
                lvRate.setIsVip("否");
                lvRate.setRate(new BigDecimal("8.00"));
                //星脉联盟的分润等级
            } else {
                lvRate = queryRate(agentId, tranTransactionInfo.getDeptId(), tranTransactionInfo.getTerminalType(), tranTransactionInfo.getIsVip());
            }
        } else if (deptId.equals(5L) || deptId.equals(6L)) {
            lvRate = queryRate(agentId, tranTransactionInfo.getDeptId(), tranTransactionInfo.getKaolaType(), tranTransactionInfo.getIsVip());
        } else {
            lvRate = queryRate(agentId, tranTransactionInfo.getDeptId(), tranTransactionInfo.getTerminalType(), tranTransactionInfo.getIsVip());
        }
        //查询到分润等级
        if (lvRate == null) {
            log.info("交易id为" + tranTransactionInfo.getTransactionId() + "，合伙人id为：" + agentId + "渠道id为：" + tranTransactionInfo.getDeptId() + "未查询到分润等级");
            return null;
        }
        return lvRate;
    }

    @Override
    public BigDecimal getRateByYhb(Long agentId, TerTerminalInfo terminalInfo, TranTransactionInfo tranTransactionInfo, BigDecimal rate) {
        if (terminalInfo.getIsYhbuse().intValue() == 1) {

            BigDecimal yhbRate;

            if (terminalInfo.getTerminalType().intValue() == 10 || terminalInfo.getTerminalType().intValue() == 11) {
                yhbRate = getJDPayRate(terminalInfo.getSn());
            } else {
                yhbRate = queryYhbRate(terminalInfo.getSn(), agentId, tranTransactionInfo.getDeptId(), tranTransactionInfo.getTerminalType(), tranTransactionInfo.getIsVip());


            }
            System.out.println(terminalInfo.getSn() + "用户宝分润" + yhbRate);
            if (rate.compareTo(yhbRate) == 1) {
                rate = rate.subtract(yhbRate);
            }

        }
        return rate;
    }

    @Override
    public BigDecimal getJDPayRate(String sn) {
        int count = transactionInfoService.selectCount(new EntityWrapper<TranTransactionInfo>().eq("sn", sn));
        if (count >= 300) {
            Page<TranTransactionInfo> page = transactionInfoService.selectPage(new Page<>(0, 300), new EntityWrapper<TranTransactionInfo>().eq("sn", sn)
                    .orderBy("transaction_date", true)
            );
            List<TranTransactionInfo> records = page.getRecords();
            Date transactionDate = records.get(records.size() - 1).getTransactionDate();

            Date date = DateUtils.addDateMonths(transactionDate, 3);

            Date today = new Date();

            if (date.compareTo(today) == 1) {
                return new BigDecimal("0.00");
            } else {
                return new BigDecimal("3.8");
            }
        } else {
            return new BigDecimal("0.00");
        }
    }

    @Override
    public Integer getGradeByTran(BigDecimal amount, Long agentId, Long deptId) {
        List<SysLvRate> levelList = queryLvList(deptId);

        Integer minResult;
        Integer maxResult;
        final BigDecimal MULTINUM = new BigDecimal("10000");
        for (SysLvRate sysLevelRate:levelList) {

            if(sysLevelRate.getMaxTurnover().compareTo(new BigDecimal("0.00"))==0){
                return sysLevelRate.getLv();
            }else {
                //月结余和当前等级达标最小值的对比 1：大于 0：等于 -1小于
                minResult = amount.compareTo(sysLevelRate.getMinTurnover().multiply(MULTINUM));
                //月结余和当前等级达标最大值的对比
                maxResult = amount.compareTo(sysLevelRate.getMaxTurnover().multiply(MULTINUM));
                //最后一次判断，只需要判断是否最后一次



                //最小值 <= 交易量 < 最大值
                if ((minResult == 1 || minResult == 0) && maxResult == -1) {
                    return  sysLevelRate.getLv();
                }
            }
        }
        return 1;
    }

    @Override
    public SysLvRate queryLvByGrade(Long deptId, Integer grade, Integer terminalType, String isVip) {
        return selectOne(new EntityWrapper<SysLvRate>().eq("dept_id",deptId).eq("lv",grade).eq("terminal_type",terminalType).eq("is_vip",isVip));
    }


}
